<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="left">
          共{{ total }}条记录
        </span>
        <template slot="right">
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import?type=employees')"
          >导入</el-button>
          <el-button size="small" type="danger" @click="handleDownload">导出</el-button>
          <el-button size="small" type="success" @click="handleDownload1">多表头导出</el-button>
          <el-button
            size="small"
            type="primary"
            @click="showDialog=true"
          >新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card v-loading="loading">
        <el-table border :data="list">
          <el-table-column
            type="index"
            :index="indexFn"
            label="序号"
            sortable=""
          />
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column prop="staffPhoto" label="头像" sortable="">
            <template #default="{row}">
              <img
                v-imageerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto|| defaultImage"
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                @click="handleImgClick(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            sortable=""
            :formatter="formatEmployment"
          />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable="" />
          <el-table-column prop="" label="账户状态" sortable="" />
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button
                type="text"
                size="small"
                @click="assignRole(row.id)"
              >角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="delEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[5,10,15,20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <AddEmployee
        :show-dialog.sync="showDialog"
        @addEmployee="getEmployeeList"
      />
      <el-dialog
        title="二维码预览图片"
        width="400px"
        :visible="showImgDialog"
        align="center"
        @close="showImgDialog=false"
      >
        <canvas ref="staffCanvas" />
      </el-dialog>
      <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>
<script>
import QrCode from 'qrcode'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee/index.vue'
import AssignRole from './components/assign-role'
import dayjs from 'dayjs'
export default {
  components: {
    AddEmployee, AssignRole
  },
  data() {
    return {
      list: [],
      page: 1,
      size: 10,
      total: 0,
      loading: false,
      showDialog: false,
      defaultImage: 'https:hrsass-49-cs-1312445828.cos.ap-shanghai.myqcloud.com/01.jpg',
      showImgDialog: false,
      showRoleDialog: false,
      userId: null
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    assignRole(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    handleImgClick(staffPhoto) {
      if (!staffPhoto) {
        this.$message.warning('该用户还未上传头像')
        return
      }
      this.showImgDialog = true
      // 数据驱动视图更新是异步的，所以要等视图更新后再获取dom元素canvas
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.staffCanvas, staffPhoto)
      })
    },
    handleDownload() {
      /**
        点击按钮, 执行函数, 导入Export2Excel库
        只要是第一次导入后, 它就会在内存中, 下次用的时候直接使用
       */
      import('@/vendor/Export2Excel').then(async excel => {
        const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
        const headersRelations = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const { rows } = await this.apis.employees.getEmployeeList({ page: 1, size: this.total })
        // 将对象数组转为二维数组
        const data = this.formatFn(rows, headersArr, headersRelations)
        // console.log(data)//没问题
        excel.export_json_to_excel({
          header: headersArr,
          data,
          filename: `${dayjs(new Date()).format('YYYY-MM-DD')}员工信息表`,
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    handleDownload1() {
      /**
        点击按钮, 执行函数, 导入Export2Excel库
        只要是第一次导入后, 它就会在内存中, 下次用的时候直接使用
       */
      import('@/vendor/Export2Excel').then(async excel => {
        const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
        const headersRelations = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        // 多表头
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        // 合并单元格
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        const { rows } = await this.apis.employees.getEmployeeList({ page: 1, size: this.total })
        // 将对象数组转为二维数组
        const data = this.formatFn(rows, headersArr, headersRelations)
        // console.log(data)//没问题
        excel.export_json_to_excel({
          header: headersArr,
          data,
          filename: `${dayjs(new Date()).format('YYYY-MM-DD')}员工信息表`,
          autoWidth: true,
          bookType: 'xlsx',
          multiHeader,
          merges
        })
      })
    },
    formatFn(rows, headersArr, headersRelations) {
      return rows.map(obj => {
        return headersArr.map(chineseKey => {
          const englishKey = headersRelations[chineseKey]
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            return dayjs(obj[englishKey]).format('YYYY-MM-DD')
          } else if (['formOfEmployment'].includes(englishKey)) {
            const obj1 = EmployeeEnum.hireType.find(item => item.id === Number(obj[englishKey]))
            return obj1 ? obj1.value : '未知'
          } else {
            return obj[englishKey]
          }
        })
      })
    },
    async getEmployeeList() {
      this.loading = true
      const res = await this.apis.employees.getEmployeeList({ page: this.page, size: this.size })
      // console.log(res)
      this.list = res.rows
      this.total = res.total
      this.loading = false
    },
    // 改变size时触发
    handleSizeChange(val) {
      this.size = val
      this.page = 1
      this.getEmployeeList()
    },
    // 改变page时触发
    handleCurrentChange(val) {
      this.page = val
      this.getEmployeeList()
    },
    indexFn(index) {
      return index + 1 + this.size * (this.page - 1)
    },
    formatEmployment(row, column, cellValue, index) {
      // 要去找 1所对应的值
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    async delEmployee(id) {
      await this.$confirm('确定要删除该员工吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await this.apis.employees.delEmployee(id)
      this.$message.success('删除成功')
      if (this.page > 1 && this.list.length === 1) {
        this.page--
      }
      this.getEmployeeList()
    }
  }
}
</script>
